/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package au.edu.swin.unilearn;

import au.edu.swin.unilearn.subject.*;
import au.edu.swin.unilearn.tutorialGroup.*;
import au.edu.swin.unilearn.assignment.*;
import au.edu.swin.unilearn.submission.*;
import au.edu.swin.unilearn.students.*;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.model.SelectItem;
import java.io.*;
import java.util.StringTokenizer;
 
/**
 *
 * @author DidierLeung
 */
public class MarkAssignmentBean
{
    private static String STAFFID = "912345X";
    @EJB
    private TutorialGroupSessionRemote tutorialGroupSession;
    @EJB
    private AssignmentSessionRemote assignmentSession;
    @EJB
    private SubmissionSessionRemote submissionSession;
    @EJB
    private StudentSessionRemote studentSession;
    @EJB
    private SubjectSessionRemote subjectSession;
    private String filterSubjectCode;
    private String subjectName;
    private String filterAssignment;
    private String assignmentName;
    private String filterStudentID;
    private List<MarkingSchemeDetails> markingScheme;
    private Integer activity_no;
    private int totalAllocatedMarks;
    private int totalMarks;
    private String comments;

    public List<SelectItem> getSubjectCodeItems()
    {
        List<SelectItem> subjectCodeItems = new ArrayList();
        for (TutorialGroup tg : tutorialGroupSession.getTutorialGroupOf(STAFFID))
        {
            Subject s = tg.getSubject();
            SelectItem si = new SelectItem(s.getSubject_code(), s.getSubject_code() + " - " + s.getSubject_name());
            subjectCodeItems.add(si);
        }
        return subjectCodeItems;
    }

    public List<SelectItem> getAssignmentItems()
    {
        List<SelectItem> assignmentItems = new ArrayList();
        System.out.println("Subject Code: " + filterSubjectCode);
        for (Assignment a : assignmentSession.getAllAssignmentForMarking(filterSubjectCode))
        {
            SelectItem si = new SelectItem(a.getAssignment_no(), a.getAssignment_no() + " - " + a.getAssignment_name());
            assignmentItems.add(si);
        }
        return assignmentItems;
    }

    public List<SelectItem> getStudentItems()
    {
        activity_no = tutorialGroupSession.getActivityNo(STAFFID, filterSubjectCode);
        List<SelectItem> studentItems = new ArrayList();
        for (Submission s : submissionSession.getUnMarkedSubmission())
        {
            Student aStudent = s.getAStudent();
            if (studentSession.isInTutorialClass(aStudent.getId(), activity_no, filterSubjectCode))
            {
                SelectItem si = new SelectItem(aStudent.getId(), aStudent.getId() + " - " + aStudent.getName());
                studentItems.add(si);
            }
        }
        return studentItems;
    }

    public String getAssignmentAvailable()
    {
        Subject s = subjectSession.getSubject(filterSubjectCode);
        this.setSubjectName(s.getSubject_name());
        if((getAssignmentItems()).size() == 0)
        {
            return "noAssignment";
        }
        return "next";
    }

    public String displayMarkingTemplate()
    {
        List<SelectItem> studentList = getStudentItems();
        System.out.println("SUBMISSION >>> " + studentList.size());
        if (studentList.size() == 0)
        {
            return "noSubmission";
        }
        else
        {
            Assignment a = assignmentSession.getAssignment(filterAssignment, filterSubjectCode);
            this.setAssignmentName(a.getAssignment_name());
            String readingFile = getMarkingSchemeTemplate();
            if (readingFile.equals("ReadOk"))
            {
                return "next";
            }
            else
            {
                return "failure";
            }
        }

    }

    private String getMarkingSchemeTemplate()
    {
        //Get the Marking Template URL
        Assignment a = assignmentSession.getAssignment(filterAssignment, filterSubjectCode);
        String markingTemplateURL = a.getMarking_template_url();

        //Read the file and create MarkingSchemeDetails object
        markingScheme = new ArrayList();
        try
        {
            FileReader fr = new FileReader(markingTemplateURL);
            BufferedReader reader = new BufferedReader(fr);
            String line = reader.readLine();
            while (line != null)
            {
                StringTokenizer tokens = new StringTokenizer(line, "^");
                String title = tokens.nextToken();
                String mark = tokens.nextToken();
                totalAllocatedMarks += (new Integer(mark)).intValue();
                MarkingSchemeDetails markingSchemeObj = new MarkingSchemeDetails(title, mark);
                while (tokens.hasMoreTokens())
                {
                    markingSchemeObj.addDetails(tokens.nextToken());
                }
                markingScheme.add(markingSchemeObj);
                line = reader.readLine();
            }
            reader.close();
            return "ReadOk";
        }
        catch (IOException ioe)
        {
            return "ReadingError";
        }
    }

    public MarkAssignmentBean()
    {
//        markingScheme = new ArrayList();
//
//        MarkingSchemeDetails markingSchemeObj = new MarkingSchemeDetails("Fan-In extraction (Base functionality)", "1");
//        markingSchemeObj.addDetails("Input argument error checking implemented");
//        markingSchemeObj.addDetails("Reports a short error if the input data file content does not match specifications");
//        markingSchemeObj.addDetails("Writes the output files in the same format as the input file");
//        markingScheme.add(markingSchemeObj);
//
//        markingSchemeObj = new MarkingSchemeDetails("Fan-In extraction (Efficiency of implementation)", "1");
//        markingSchemeObj.addDetails("Appropriate data structures (i.e. Java collections classes) have been selected and used effectively");
//        markingSchemeObj.addDetails("Performance when running with 10,000 lines of input data is good");
//        markingScheme.add(markingSchemeObj);
    }

    public List<MarkingSchemeDetails> getMarkingScheme()
    {
        return markingScheme;
    }

    public void setMarkingScheme(List<MarkingSchemeDetails> markingScheme)
    {
        this.markingScheme = markingScheme;
    }

    public String getComments()
    {
        return comments;
    }

    public void setComments(String comments)
    {
        this.comments = comments;
    }

    public String submitMarking()
    {
        String fileOnServerURL = saveFile();
        if (fileOnServerURL.equals("saveFailure"))
        {
            return "failure";
        }

        try
        {
            submissionSession.updateSubmission(filterStudentID, filterAssignment,
                                               filterSubjectCode, fileOnServerURL, totalMarks);

            return "success";
        }
        catch (Exception e)
        {
            return "failure";
        }

    }

    private String saveFile()
    {
        //write to txt file
        try
        {
            String rootFileSystem = "Unilearn_Storage/" + filterSubjectCode +
                    "/Submission/TutorialGroup_" + activity_no + "/Assignment_" + filterAssignment;
            String fileOnServerURL = rootFileSystem + "/" + filterStudentID + "_MarkingDetails.txt";
            FileWriter fw = new FileWriter(fileOnServerURL);
            PrintWriter out = new PrintWriter(fw);
            out.println("Provisional Marks for:");
            out.println("Subject    : " + filterSubjectCode + " - " + subjectName);
            out.println("Assessment : Assessment " + filterAssignment + " - " + assignmentName);
            out.println("Student    : " + getStudentName() + "(" + filterStudentID + ")");
            out.println();
            out.println("Assessment " + filterAssignment + " - " + assignmentName +
                        " submitted on " + getSubmissionDate());
            out.println();
            out.println("----------------------------------------------------------------");
            totalMarks = 0;
            for (MarkingSchemeDetails m : markingScheme)
            {
                totalMarks += m.writeDetails(out);
            }
            out.println("Comments:");
            out.println(comments);
            out.println("----------------------------------------------------------------");
            out.println("Total Provisional Marks: " + totalMarks + "/" + totalAllocatedMarks);
            out.println("----------------------------------------------------------------");
            out.println();
            out.println("Tutor Mark     = " + totalMarks + "/" + totalAllocatedMarks);
            out.println("----------------------------------------------------------------");
            out.println("Overall Mark   = " + totalMarks + "/" + totalAllocatedMarks);
            out.println("Late Penalty   = Not Applicable");
            out.println("----------------------------------------------------------------");
            out.println("Final Mark     = " + totalMarks + "/" + totalAllocatedMarks);
            out.println("----------------------------------------------------------------");

            out.close();
            return fileOnServerURL;
        }
        catch (IOException ioe)
        {
            return "saveFailure";
        }
    }

    public String markMoreSubmission()
    {
        for (MarkingSchemeDetails m : markingScheme)
        {
            m.resetMark();
        }
        List<SelectItem> studentList = getStudentItems();
        System.out.println("SUBMISSION >>> " + studentList.size());
        if (studentList.size() == 0)
        {
            return "noSubmission";
        }
        return "markMoreSubmission";
    }

    private String getStudentName()
    {
        Student s = studentSession.getStudent(filterStudentID);
        return s.getName();
    }

    private String getSubmissionDate()
    {
        Submission s = submissionSession.getSubmission(
                filterStudentID, filterAssignment, filterSubjectCode);
        return (s.getSubmitted_date()).toString();
    }

    public String getFilterSubjectCode()
    {
        return filterSubjectCode;
    }

    public void setFilterSubjectCode(String filterSubjectCode)
    {
        this.filterSubjectCode = filterSubjectCode;
    }

    public String getFilterAssignment()
    {
        return filterAssignment;
    }

    public void setFilterAssignment(String filterAssignment)
    {
        this.filterAssignment = filterAssignment;
    }

    public String getFilterStudentID()
    {
        return filterStudentID;
    }

    public void setFilterStudentID(String filterStudentID)
    {
        this.filterStudentID = filterStudentID;
    }

    public String getSubjectName()
    {
        return subjectName;
    }

    public void setSubjectName(String subjectName)
    {
        this.subjectName = subjectName;
    }

    public String getAssignmentName()
    {
        return assignmentName;
    }

    public void setAssignmentName(String assignmentName)
    {
        this.assignmentName = assignmentName;
    }

    public Integer getActivity_no()
    {
        return activity_no;
    }

    public void setActivity_no(Integer activity_no)
    {
        this.activity_no = activity_no;
    }
}
